package com.gmall.security.controller;

import com.alibaba.fastjson.JSONObject;
import com.gmall.common.enums.HttpBizCode;
import com.gmall.common.model.Response;
import com.gmall.user.api.po.User;
import com.gmall.user.api.provider.UserClient;
import com.google.common.base.Preconditions;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;

/**
 * @author HL.Wu
 * @date 2020/5/25 15:33
 * Copyright ©https://blog.csdn.net/qq_31150503 Copyright@2009-2020 AII Right Reserve
 */
@RestController
@RequestMapping("/user")
@Slf4j
public class AuthController {

    @Autowired
    private BCryptPasswordEncoder bCryptPasswordEncoder;

    @Autowired
    private UserClient userClient;

    @PostMapping("/register")
    public Response register(@RequestBody JSONObject jsonObject){
        Response response = Response.newInstance();
        try {
            // 校验名字是否存在
            User ut = userClient.findUserByName(jsonObject.getString("userName"));
            Preconditions.checkArgument(ut == null ,"抱歉，用户名已存在");
            // 用户密码加密
            jsonObject.put("password",bCryptPasswordEncoder.encode(jsonObject.getString("password")));
            //user.setRoleList(Arrays.asList("ROLE_ADMIn","ROLE_GUEST"));
            int j = userClient.save(jsonObject);
            Preconditions.checkArgument(j > 0 ,"抱歉，注册失败");
            User ur = userClient.findUserByName(jsonObject.getString("userName"));
            response.fill(HttpBizCode.SUCCESS,HttpBizCode.SUCCESS.getText());
        }catch (IllegalArgumentException e){
            response.fail(HttpBizCode.BIZERROR,e.getMessage());
            log.error("is error {}",e);
        }catch (Exception e){
            response.fail(HttpBizCode.BIZERROR,HttpBizCode.BIZERROR.getText());
            log.error("is error {}",e);
        }
        return response;
    }

    /**
     * 注销设置删除token信息 重置过期时间
     *
     * @param request
     */
    @PostMapping("/logout")
    public Response loginOut(HttpServletRequest request){
        Response response = Response.newInstance();
        return response.fill(HttpBizCode.SUCCESS,HttpBizCode.SUCCESS.getText());
    }
}
